package paidaxing.blog.user.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import paidaxing.blog.common.exception.BusinessException;
import paidaxing.blog.common.result.Result;
import paidaxing.blog.user.dto.UpdateUserRequest;
import paidaxing.blog.user.dto.UserDTO;
import paidaxing.blog.user.dto.UserRequest;
import paidaxing.blog.user.service.UserService;

import java.util.Map;

/**
 * 用户信息管理控制层
 *
 * @author heefM
 * @date 2025-10-18
 */
@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {


    @Autowired
    private UserService userService;

    /**
     * 获取用户信息
     */
    @GetMapping("/{userId}")
    public Result<UserDTO> getUserInfo(@PathVariable Long userId) {
        UserDTO userDTO = userService.getUserInfo(userId);

        // 如果不是查看自己，隐藏敏感信息
        try {
            Long currentUserId = StpUtil.getLoginIdAsLong();
            if (!userId.equals(currentUserId)) {
                this.removeSensitiveInfo(userDTO);
            }
        } catch (Exception e) {
            // 未登录用户查看，直接隐藏敏感信息
            this.removeSensitiveInfo(userDTO);
        }

        return Result.success(userDTO);
    }

    /**
     * 更新用户信息
     */
    @SaCheckLogin
    @PutMapping("/{userId}")
    public Result<UserDTO> updateUserInfo(
            @PathVariable Long userId,
            @Valid @RequestBody UpdateUserRequest request) {

        // 权限校验：只能修改自己的信息
        Long currentUserId = StpUtil.getLoginIdAsLong();
        if (!currentUserId.equals(userId) && !StpUtil.hasRole("ADMIN")) {
            throw new BusinessException("无权修改其他用户信息");
        }

        UserDTO userDTO = userService.updateUserInfo(userId, request);
        return Result.success(userDTO);
    }

    /**
     * 获取用户文章列表
     */
    @GetMapping("/{userId}/posts")
    public Result<Map<String, Object>> getUserPosts(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {

        Map<String, Object> result = userService.getUserPosts(userId, page, size);
        return Result.success(result);
    }

    /**
     * 更新用户头像
     */
    @SaCheckLogin
    @PutMapping("/{userId}/avatar")
    public Result<String> updateAvatar(
            @PathVariable Long userId,
            @RequestParam String avatarUrl) {

        // 权限校验
        Long currentUserId = StpUtil.getLoginIdAsLong();
        if (!currentUserId.equals(userId)) {
            throw new BusinessException("无权修改其他用户头像");
        }

        userService.updateAvatar(userId, avatarUrl);
        return Result.success("头像更新成功");
    }

    /**
     * 用户数据统计
     */
    @GetMapping("/{userId}/stats")
    public Result<Map<String, Object>> getUserStats(@PathVariable Long userId) {
        Map<String, Object> stats = userService.getUserStats(userId);
        return Result.success(stats);
    }


    /**
     * 移除用户敏感信息
     * @param userDTO
     */
    private void removeSensitiveInfo(UserDTO userDTO){
        userDTO.setPassword(null);
        userDTO.setEmail(null);
        userDTO.setLastLoginTime(null);
    }


}
